package top.lvkun.product.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.lvkun.basic.utils.AjaxResult;
import top.lvkun.basic.utils.PageList;
import top.lvkun.basic.utils.RedisUtils;
import top.lvkun.org.domain.Employee;
import top.lvkun.product.domain.Product;
import top.lvkun.product.query.ProductQuery;
import top.lvkun.product.service.IProductService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    /**
     * 分页查询+ 高级条件查询
     * @param productQuery
     * @return
     */
    @PostMapping
    public PageList<Product> pageList(@RequestBody ProductQuery productQuery, HttpServletRequest request){
        //获取当前登录用户
        Employee employee = RedisUtils.INSTANCE.getUser(request, Employee.class);
        //设置当前查看的商品为后台管理系统当前登录的门店管理员
        productQuery.setShop_id(employee.getShop().getId());
        return productService.queryData(productQuery);
    }

    /**
     * 新增产品及修改产品信息
     * @param product
     * @param request
     * @return
     */
    @PutMapping
    public AjaxResult AddOrUpdate(@RequestBody Product product, HttpServletRequest request){
        System.out.println(product.getProductDetail());
        try {
            //获取当前登录用户
            Employee employee = RedisUtils.INSTANCE.getUser(request, Employee.class);
            //设置当前查看的商品为后台管理系统当前登录的门店管理员
            product.setShop_id(employee.getShop().getId());
            productService.AddOrUpdate(product);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("提交失败！");
        }

    }

    /**
     * 删除产品
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            productService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务繁忙！");
        }
    }

    @PatchMapping("/up")
    public AjaxResult productUp(@RequestBody List<Long> ids){
        try {
            productService.patchUp(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务繁忙!");
        }
    }

    @PatchMapping("/down")
    public AjaxResult productDown(@RequestBody List<Long> ids){
        try {
            productService.patchDown(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("服务繁忙!");
        }
    }

}
